package com.mymarkdown.app.controller;

import com.mymarkdown.app.interfaces.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mymarkdown.app.util.ReadFileImageUtil;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zenglun
 * @date 2021/12/10 10:20 上午
 * @description: TODO
 */
@Slf4j
@Controller
public class NotFoundExceptionController extends AbstractErrorController {

    @Autowired
    private UserInfoService userInfoService;

    public NotFoundExceptionController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
        //  Auto-generated constructor stub
    }


    @Override
    public String getErrorPath() {
        return "/error";
    }

    /**
     * 对图片资源的访问，如果没有找到相关资源,则从指定路径下去寻找
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = {"/error"})
    public void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> errorAttributes = getErrorAttributes(request, true);
        log.error("[NotFoundExceptionController]---[error],请求路径:{}资源未找到!", errorAttributes.get("path"));
        if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
            String requestURI = MapUtil.getStr(errorAttributes, "path");
            log.info("[NotFoundExceptionController]---[error],404,URL:{}", requestURI);
            // 首先获取当前操作的文件
            BlockingQueue<File> operationFile = userInfoService.getOperationFile();
            File file = operationFile.peek();
            if (Objects.isNull(file)) {
                return;
            }
            // 如果当前文件不等于null,则开始处理
            if (StrUtil.startWith(requestURI, "/")) {
                // 如果以/开头表示访问的根路径
                File dirFile = new File(requestURI);
                if (dirFile.exists()) {
                    ReadFileImageUtil.showImage(dirFile.getPath(), response);
                    return;
                } else {
                    // 如果不存在,则可能是通过/view方法
                    dirFile = new File(file.getParent() + requestURI.replace("/view", ""));
                    if (dirFile.exists()) {
                        response.setStatus(HttpServletResponse.SC_OK);
                        ReadFileImageUtil.showImage(dirFile.getPath(), response);
                    }
                }
            }
        }
        return;
    }

}
